#include "graphicwindow.h"
#include <QHBoxLayout>
#include <QPushButton>
#include <QKeyEvent>
GraphicMainWindow::GraphicMainWindow(QWidget *parent)
                :QMainWindow(parent)
                ,m_pmyGraphicView(nullptr)
                ,m_eSelectShape(eNodeSelect)
                ,m_bfirstAdd(false)
{

    initUi();
    // 安装事件过滤器到父对象
    this->installEventFilter(this);
    // 安装事件过滤器到子对象
    m_rectbutton->installEventFilter(this);
}

GraphicMainWindow::~GraphicMainWindow()
{

}

bool GraphicMainWindow::eventFilter(QObject *watched, QEvent *event)
{
    if (event->type() == QEvent::MouseButtonPress)
    {
        QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
        if (mouseEvent->button() == Qt::LeftButton) {
            if(watched == m_rectbutton)
            {
                m_eSelectShape = eSelectShape::eRectTangle;
                m_bfirstAdd = false;
            }
        }
    }
    else if(event->type() == QEvent::MouseButtonRelease)
    {
        m_bfirstAdd = false;
        m_eSelectShape = eSelectShape::eNodeSelect;
    }
    else if(event->type() == QEvent::MouseMove)
    {
        QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
        QPoint point = mouseEvent->pos();
        if(m_eSelectShape == eSelectShape::eRectTangle
            && m_pmyGraphicView->geometry().contains(point)
            && !m_bfirstAdd)
        {
            m_bfirstAdd = true;
            m_pmyGraphicView->addNode(m_eSelectShape, point);
        }
        else if(m_bfirstAdd)
        {
            m_pmyGraphicView->setPos(point);

        }
    }

    // 默认事件处理
    return QMainWindow::eventFilter(watched, event);
}

void GraphicMainWindow::mouseMoveEvent(QMouseEvent *event)
{
    QMainWindow::mouseMoveEvent(event);
    //static int a = 0;
    //qDebug() << a++;
}

void GraphicMainWindow::initUi()
{
    QWidget* mainWidget = new QWidget(this);

    QHBoxLayout* mainLayout = new QHBoxLayout();
    mainLayout->setSpacing(5);
    m_rectbutton = new QPushButton(this);
    m_rectbutton->setFixedSize(120, 60);
    m_rectbutton->setText("矩形");
    m_rectbutton->setFocusPolicy(Qt::NoFocus);
    mainLayout->addWidget(m_rectbutton);

    m_pmyGraphicView = new MyGraphicView(this);
    mainLayout->addWidget(m_pmyGraphicView);

    mainWidget->setLayout(mainLayout);
    mainWidget->setMouseTracking(true);
    setMouseTracking(true);
    setCentralWidget(mainWidget);
}
